<!--
 * @Author: Wangtao
 * @Date: 2022-08-12 17:45:05
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-22 17:09:21
-->
<template>
  <div class="login-container">
    <div class="login-left">
      <div class="left-box">
        <div class="left-title">欢迎登录</div>
        <div class="left-info">为企业量身定制的“全场景全流程”管理系统</div>
        <img :src="LoginBg" />
      </div>
    </div>
    <div class="login-right">
      <div class="right-top">
        <img :src="Logo" />
      </div>
      <div class="right-box">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="top"
          hide-required-asterisk
          :size="'default'"
        >
          <div class="title-container">
            <h3 class="title">登录</h3>
          </div>

          <el-form-item prop="loginName" label="账号">
            <!-- <span class="svg-container">
              <i class="el-icon-user" />
            </span> -->
            <el-input
              ref="userNameRef"
              v-model.trim="loginForm.loginName"
              :placeholder="'用户名'"
              name="loginName"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-form-item prop="password" label="密码">
            <span class="svg-container">
              <i class="el-icon-lock" />
            </span>
            <el-input
              :key="passwordType"
              ref="passwordRef"
              v-model.trim="loginForm.password"
              :type="passwordType"
              :placeholder="'登录密码'"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter="handleLogin(loginFormRef)"
            />
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click.prevent="handleLogin(loginFormRef)"
          >
            立即登录
          </el-button>
        </el-form>
        <div class="login-oprate">
          <div><el-checkbox v-model="remember" @change="rememberChange">记住密码</el-checkbox></div>
          <div>
            <el-checkbox v-model="policy" class="policy-checkbox-wrap">
              <span>
                我已阅读并同意
                <a :href="getPlatformConfig.m7ServiceTerms" target="_blank">《服务协议》</a>和<a
                  :href="getPlatformConfig.m7PrivacyPolicy"
                  target="_blank"
                  >《隐私政策》</a
                >
              </span>
            </el-checkbox>
          </div>
        </div>
        <!-- <div>测试账号： 2000@mc1 测试密码: 123456Aa</div> -->
      </div>
      <div class="right-bottom login-footer">
        <!-- <p class="serve-number">客服服务热线：4008-113-114 / 010-80455555</p> -->
        <div class="contact">
          <p class="serve-number">客服服务热线：4001-113-114</p>
          <p>技术支持邮箱：service@7moor.com</p>
        </div>
        <div class="record-number">
          增值电信业务经营许可证B2-20213887<span class="footer-circle">·</span>©<span>{{ currentYear }}</span
          >容联七陌<span class="footer-circle">·</span>京ICP备140006443号-1
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs, nextTick, onMounted } from 'vue'

import { userModule } from '@/common/store/modules/user'

import { useRouter, useRoute } from 'vue-router'

import LoginBg from '@/common/assets/login/login-bg.svg'

import Logo from '@/common/assets/login/7moor-logo.svg'
import { ElMessage } from 'element-plus'
const validateUsername = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入正确的用户名'))
  } else {
    const trimValue = value.trim()
    if (!trimValue) {
      callback(new Error('请输入正确的用户名'))
    } else {
      callback()
    }
  }
}

const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

export default defineComponent({
  name: 'login-container',
  components: {},
  // ----------------生命周期-----------------------
  setup() {
    // ----------------传入属性-----------------------
    // ----------------内部属性-----------------------
    const userNameRef = ref(null)
    const passwordRef = ref(null)
    const loginFormRef: any = ref(null)
    const USERMODULE = userModule()
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      loginForm: {
        loginName: '',
        password: ''
      },
      loginRules: {
        loginName: [{ validator: validateUsername, trigger: 'blur', required: true }],
        password: [{ validator: validatePassword, trigger: 'blur', required: true }]
      },
      passwordType: 'password',
      loading: false,
      showDialog: false,
      capsTooltip: false,
      redirect: '',
      otherQuery: {},
      remember: false,
      policy: false,
      getPlatformConfig: {
        m7ServiceTerms: 'https://m.7moor.com/static/m7ServiceTerms.html',
        m7PrivacyPolicy: 'https://m.7moor.com/static/m7PrivacyPolicy.html'
      }
    })
    // ----------------计算属性-----------------------
    // ----------------监听方法-----------------------
    // ----------------调用方法-----------------------
    const methods = reactive({
      validateUsername: (rule: any, value: string, callback: any) => {
        callback()
      },
      validatePassword: (rule: any, value: string, callback: any) => {
        if (value.length < 6) {
          callback(new Error('The password can not be less than 6 digits'))
        } else {
          callback()
        }
      },
      checkCapslock: (e: KeyboardEvent) => {
        const { key } = e
        state.capsTooltip = key !== null && key.length === 1 && key >= 'A' && key <= 'Z'
      },
      showPwd: () => {
        if (state.passwordType === 'password') {
          state.passwordType = ''
        } else {
          state.passwordType = 'password'
        }
        nextTick(() => {
          ;(passwordRef.value as any).focus()
        })
      },
      handleLogin: (formEl: any) => {
        if (!formEl) return
        formEl.validate(async (valid: boolean) => {
          if (valid) {
            if (!state.policy) {
              ElMessage.error('请阅读并同意《服务协议》和《隐私政策》')
              return
              // 没有勾选协议，不可以登录
            }
            state.loading = true
            const query: any = route.query
            await USERMODULE.handleLogin({ ...state.loginForm }).catch(() => {
              state.loading = false
            }).then(async (loginState) => {
               if (loginState) {
                  window.name = `${loginState.accountId}-${loginState.clientType === 0 ? 'admin' : 'agent'}` // 登录页赋值一次，避免切换工作台的时候，有3个
                  if (state.remember) {
                    await USERMODULE.rememberLogininfo(JSON.stringify(state.loginForm), 'loginInfo')
                  }
                  await USERMODULE.rememberLogininfo(JSON.stringify({ policy: state.policy }), 'otherInfo')
              }
              router.push({
                path: query.redirect || '/'
              })
            })
          } else {
            state.loading = false
          }
        })
      },
      async rememberChange(value: boolean) {
        if (!value) {
          await USERMODULE.forgetLoginInfo()
        }
      },
      async getRememberInfo() {
        const RRMEMBERINFO = await USERMODULE.getRememberInfo('loginInfo')
        const OTHERINFO = await USERMODULE.getRememberInfo('otherInfo')
        if (RRMEMBERINFO) {
          state.remember = true
          state.loginForm = RRMEMBERINFO
        }
        state.policy = (OTHERINFO && OTHERINFO.policy) || false
      }
    })

    onMounted(async () => {
      methods.getRememberInfo()
    })
    return {
      userNameRef,
      passwordRef,
      loginFormRef,
      ...toRefs(state),
      ...toRefs(methods),
      LoginBg,
      Logo
    }
  }
})
</script>
<style lang="stylus">
.login-container
  .el-form-item__label
    color rgba(0, 0, 0, 0.88)
body.login-loading
  background #fff
</style>
<style lang="stylus" scoped>
.login-container
  width 100%
  height 100%
  position fixed
  display flex
  flex-direction row
  .login-left
    width 38%
    display flex
    flex-direction column
    align-items center
    box-sizing border-box
    justify-content center
    border-right 1px solid rgba(0, 0, 0, 0.1)
    .left-box
      display flex
      flex-direction column
      align-items flex-start
    .left-title
      font-weight 500
      font-size 32px
      margin-bottom 16px
    .left-info
      font-weight 400
      font-size 12px
      background-color #F0F2FA
      color rgba(0, 0, 0, 0.6)
      padding 8px 16px 8px
      box-sizing border-box
      margin-bottom 40px
  .login-right
    width 62%
    display flex
    flex-direction column
    align-items center
    justify-content space-between
    .right-top
      width 100%
      padding 56px 56px 0
      box-sizing border-box
    .right-bottom
      color rgba(0, 0, 0, 0.38)
      font-weight 400
      font-size 14px
      display flex
      flex-direction column
      padding-bottom 56px
      .contact
        display flex
        justify-content space-between
  .title-container
    .title
      // text-align center
      font-size 24px
      font-weight 500
</style>
